package br.usp.poli.dao;

import java.io.Serializable;
import java.util.List;
import java.util.logging.Logger;

import org.hibernate.Session;
import org.hibernate.exception.ConstraintViolationException;

public class GenericDao<T, ID extends Serializable> {
	private Logger log = Logger.getLogger(GenericDao.class.getName());
	private Class<T> persistentClass;
	private Session session;

	public void saveOrUpdate(T t) {
		session.saveOrUpdate(t);
	}

	public static <T, ID extends Serializable> GenericDao<T, ID> getInstance(
			Session session, Class<T> classe) {
		return new GenericDao<T, ID>(session, classe);
	}

	private GenericDao(Session session, Class<T> persistentClass) {
		super();
		this.session = session;
		this.persistentClass = persistentClass;
	}

	@SuppressWarnings("unchecked")
	public T load(ID id) {
		log.info("Lendo " + persistentClass + " com " + id);
		return (T) session.load(persistentClass, id);
	}

	public void save(T t) {
		log.info("salvando " + t);
		try {
			session.save(t);
		} catch (ConstraintViolationException e) {
			log.severe(e.getMessage());
		}
	}

	public void delete(T t) {
		log.info("Deletando " + t);
		session.delete(t);
	}

	@SuppressWarnings("unchecked")
	public List<T> list() {
		log.info("Listando todos " + persistentClass);
		return session.createCriteria(persistentClass).list();
	}

	public void merge(T t) {
		log.info("Salvando ou atualizando " + t);
		session.merge(t);
	}
}
